package com.fjwt.gz.sync.notify;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.exception.ResponseException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.interfaces.ChannelCouponWriteService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api/couponWriteOff")
public class CouponWriteOffNotify {

    private static final Logger ysPayLogger = LoggerFactory.getLogger("ysPay");
    private static final Logger tlPayLogger = LoggerFactory.getLogger("tlPay");
    private static final Logger hkPayLogger = LoggerFactory.getLogger("hkPay");
    private static final Logger gtPayLogger = LoggerFactory.getLogger("gtPay");

    @Autowired
    private LklsCouponWriteOffNotifyService lklsNotifyService;

    private static String logPrefix = "卡券核销接口";

    @RequestMapping(value = {"/notify/yspay", "/return/yspay/{couponId}"}, method = RequestMethod.POST)
    public String yspaySyncPayOrder(HttpServletRequest request,@PathVariable(value = "urlCouponId", required = false) String urlCouponId) {
        String ifCode = "yspay";
        JSONObject respJson = new JSONObject();
        String apiRes = null;
        String couponId = null;
        String logPrefix = "进入[" + ifCode + "]卡券核销同步跳转：urlCouponId：[" + StringUtils.defaultIfEmpty(urlCouponId, "") + "] ";
        ysPayLogger.info("===== {} =====", logPrefix);

        try {
            // 参数有误
            if (StringUtils.isEmpty(ifCode)) {
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调参数有误");
                ysPayLogger.info(logPrefix + "回调参数有误,ifcode不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            }

            //查询支付接口是否存在
            ChannelCouponWriteService channelCouponWriteService = SpringBeansUtil.getBean(ifCode + "CouponWriteService", ChannelCouponWriteService.class);

            // 支付通道接口实现不存在
            if (channelCouponWriteService == null) {
                ysPayLogger.info("卡券核销回调，{}, interface not exists ", logPrefix);
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调失败");
                ysPayLogger.info(logPrefix + "支付通道接口实现不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
                return JSONUtil.toJsonStr(respJson);
            }

            //判断卡券是否是在营销平台创建
            Map<String, Object> reqMap = channelCouponWriteService.paraseParamters(request);
            ysPayLogger.info(logPrefix + "解析参数返回的信息是：{}",JSONUtil.toJsonStr(reqMap));

            apiRes = channelCouponWriteService.addNotifyRecord(reqMap);
            ysPayLogger.info(ifCode + "返回的信息是：{}", JSONUtil.toJsonStr(apiRes));

            return apiRes;
        } catch (BizException e) {
            ysPayLogger.error("{}, couponId={}, BizException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            ysPayLogger.info(logPrefix + "1返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONUtil.toJsonStr(respJson);
        } catch (ResponseException e) {
            ysPayLogger.error("{}, couponId={}, ResponseException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            ysPayLogger.info(logPrefix + "2返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONUtil.toJsonStr(respJson);
        } catch (Exception e) {
            ysPayLogger.error("{}, couponId={}, 系统异常", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            ysPayLogger.info(logPrefix + "3返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONUtil.toJsonStr(respJson);
        }
    }



    @RequestMapping(value = {"/notify/tlpay", "/return/tlpay/{couponId}"}, method = RequestMethod.POST)
    public ApiRes tlpaySyncPayOrder(HttpServletRequest request, @PathVariable(value = "urlCouponId", required = false) String urlCouponId) {
        String ifCode = "tlpay";
        JSONObject respJson = new JSONObject();
        String apiRes = null;
        String couponId = null;
        String logPrefix = "进入[" + ifCode + "]卡券核销同步跳转：urlCouponId：[" + StringUtils.defaultIfEmpty(urlCouponId, "") + "] ";
        tlPayLogger.info("===== {} =====", logPrefix);

        try {
            // 参数有误
            if (StringUtils.isEmpty(ifCode)) {
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调参数有误");
                tlPayLogger.info(logPrefix + "回调参数有误,ifcode不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            }

            //查询支付接口是否存在
            ChannelCouponWriteService channelCouponWriteService = SpringBeansUtil.getBean(ifCode + "CouponWriteService", ChannelCouponWriteService.class);

            // 支付通道接口实现不存在
            if (channelCouponWriteService == null) {
                tlPayLogger.info("卡券核销回调，{}, interface not exists ", logPrefix);
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调失败");
                tlPayLogger.info(logPrefix + "支付通道接口实现不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
                return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
            }

            //判断卡券是否是在营销平台创建
            Map<String, Object> reqMap = channelCouponWriteService.paraseParamters(request);
            tlPayLogger.info(logPrefix + "解析参数返回的信息是：{}",JSONUtil.toJsonStr(reqMap));

            apiRes = channelCouponWriteService.addNotifyRecord(reqMap);
            tlPayLogger.info(ifCode + "返回的信息是：{}", JSONUtil.toJsonStr(apiRes));
            ApiRes apiResp = JSONObject.parseObject(apiRes, ApiRes.class);
            return apiResp;
        } catch (BizException e) {
            tlPayLogger.error("{}, couponId={}, BizException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            tlPayLogger.info(logPrefix + "1返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
        } catch (ResponseException e) {
            tlPayLogger.error("{}, couponId={}, ResponseException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            tlPayLogger.info(logPrefix + "2返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
        } catch (Exception e) {
            tlPayLogger.error("{}, couponId={}, 系统异常", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            tlPayLogger.info(logPrefix + "3返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
        }
    }



    @RequestMapping(value = {"/notify/wx", "/return/wx/{couponId}"}, method = RequestMethod.POST)
    public String WxSyncPayOrder(HttpServletRequest request, @PathVariable(value = "urlCouponId", required = false) String urlCouponId) {
        String ifCode = "wx";
        JSONObject respJson = new JSONObject();
        String apiRes = null;
        String couponId = null;
        String logPrefix = "进入[" + ifCode + "]卡券核销同步跳转：urlCouponId：[" + StringUtils.defaultIfEmpty(urlCouponId, "") + "] ";
        log.info("===== {} =====", logPrefix);

        try {
            // 参数有误
            if (StringUtils.isEmpty(ifCode)) {
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调参数有误");
                log.info(logPrefix + "回调参数有误,ifcode不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            }

            //查询支付接口是否存在
            ChannelCouponWriteService channelCouponWriteService = SpringBeansUtil.getBean(ifCode + "CouponWriteService", ChannelCouponWriteService.class);

            // 支付通道接口实现不存在
            if (channelCouponWriteService == null) {
                log.info("卡券核销回调，{}, interface not exists ", logPrefix);
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调失败");
                log.info(logPrefix + "支付通道接口实现不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
                return JSONUtil.toJsonStr(respJson);
            }

            //判断卡券是否是在营销平台创建
            Map<String, Object> reqMap = channelCouponWriteService.paraseParamters(request);
            log.info(logPrefix + "解析参数返回的信息是：{}",JSONUtil.toJsonStr(reqMap));

            apiRes = channelCouponWriteService.addNotifyRecord(reqMap);
            log.info(ifCode + "返回的信息是：{}", JSONUtil.toJsonStr(apiRes));

            return apiRes;
        } catch (BizException e) {
            log.error("{}, couponId={}, BizException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            log.info(logPrefix + "1返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONUtil.toJsonStr(respJson);
        } catch (ResponseException e) {
            log.error("{}, couponId={}, ResponseException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            log.info(logPrefix + "2返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONUtil.toJsonStr(respJson);
        } catch (Exception e) {
            log.error("{}, couponId={}, 系统异常", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            log.info(logPrefix + "3返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONUtil.toJsonStr(respJson);
        }
    }

    /**
     * 海科卡券核销回调
     * @param request
     * @return
     */
    @PostMapping("/notify/hk")
    public String HkSyncPayOrder(@RequestParam Map<String, Object> request) {
        String ifCode = "hkpay";
        String result = "FAIL";

        String logPrefix = "进入[" + ifCode + "]卡券核销回调";
        hkPayLogger.info("===== {} =====", logPrefix);

        try {
            // 参数有误
            if (StringUtils.isEmpty(ifCode)) {
                hkPayLogger.info(logPrefix + "回调参数有误,ifcode不存在,返回的信息是：{}", result);
                return result;
            }

            //查询支付接口是否存在
            ChannelCouponWriteService channelCouponWriteService = SpringBeansUtil.getBean(ifCode + "CouponWriteService", ChannelCouponWriteService.class);

            // 支付通道接口实现不存在
            if (channelCouponWriteService == null) {
                hkPayLogger.info(logPrefix + "支付通道接口实现不存在,返回的信息是：{}", result);
                return "FAIL";
            }

            result = channelCouponWriteService.addNotifyRecord(request);
            hkPayLogger.info(ifCode + "返回的信息是：{}", result);

            return result;
        } catch (Exception e) {
            hkPayLogger.info(logPrefix + "系统异常：{}", e.getMessage());
            return "FAIL";
        }
    }


    /**
     * 拉卡拉核销回调入口
     * @param request
     * @return
     */
    @PostMapping(value="/notify/lklspay",produces = MediaType.TEXT_PLAIN_VALUE)
    public String lklspaySyncPayOrder(HttpServletRequest request) {
        String res = lklsNotifyService.lklspaySyncPayOrder(request);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("res",res);
        return JSONUtil.toJsonStr(jsonObject);
    }

    @RequestMapping(value = {"/notify/gtpay", "/return/gtpay/{couponId}"}, method = RequestMethod.POST)
    public ApiRes gtpaySyncPayOrder(HttpServletRequest request, @PathVariable(value = "urlCouponId", required = false) String urlCouponId) {
        String ifCode = "gtpay";
        JSONObject respJson = new JSONObject();
        String apiRes = null;
        String couponId = null;
        String logPrefix = "进入[" + ifCode + "]卡券核销同步跳转：urlCouponId：[" + StringUtils.defaultIfEmpty(urlCouponId, "") + "] ";
        gtPayLogger.info("===== {} =====", logPrefix);

        try {
            // 参数有误
            if (StringUtils.isEmpty(ifCode)) {
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调参数有误");
                gtPayLogger.info(logPrefix + "回调参数有误,ifcode不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            }

            //查询支付接口是否存在
            ChannelCouponWriteService channelCouponWriteService = SpringBeansUtil.getBean(ifCode + "CouponWriteService", ChannelCouponWriteService.class);

            // 支付通道接口实现不存在
            if (channelCouponWriteService == null) {
                gtPayLogger.info("卡券核销回调，{}, interface not exists ", logPrefix);
                respJson.put("code",500);
                respJson.put("msg","FAIL");
                respJson.put("data","回调失败");
                gtPayLogger.info(logPrefix + "支付通道接口实现不存在,返回的信息是：{}", JSONUtil.toJsonStr(respJson));
                return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
            }

            //判断卡券是否是在营销平台创建
            Map<String, Object> reqMap = channelCouponWriteService.paraseParamters(request);
            gtPayLogger.info(logPrefix + "解析参数返回的信息是：{}",JSONUtil.toJsonStr(reqMap));

            apiRes = channelCouponWriteService.addNotifyRecord(reqMap);
            gtPayLogger.info(ifCode + "返回的信息是：{}", JSONUtil.toJsonStr(apiRes));
            ApiRes apiResp = JSONObject.parseObject(apiRes, ApiRes.class);
            return apiResp;
        } catch (BizException e) {
            gtPayLogger.error("{}, couponId={}, BizException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            gtPayLogger.info(logPrefix + "1返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
        } catch (ResponseException e) {
            gtPayLogger.error("{}, couponId={}, ResponseException", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            gtPayLogger.info(logPrefix + "2返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
        } catch (Exception e) {
            gtPayLogger.error("{}, couponId={}, 系统异常", logPrefix, couponId, e);
            respJson.put("code",500);
            respJson.put("msg","FAIL");
            respJson.put("data","回调失败");
            gtPayLogger.info(logPrefix + "3返回的信息是：{}", JSONUtil.toJsonStr(respJson));
            return JSONObject.parseObject(JSONUtil.toJsonStr(respJson), ApiRes.class);
        }
    }


}
